﻿#include "udpchanneldemo.h"
#include <net/udpchannel.h>
#include <QDateTime>
#include <QTimerEvent>

using namespace QtSocket;

UdpChannelDemo::UdpChannelDemo(QObject *parent) : QObject(parent)
{
    m_session = Q_NULLPTR;
    m_timerID = 0;
}

bool UdpChannelDemo::start(QHostAddress &remoteIP, quint16 remotePort, QHostAddress &localIP, quint16 localPort)
{
    m_session  = new UdpChannel;
    bool binded = m_session->bind(localIP, localPort);
    if(binded)
    {
        m_session->setReading(this);
        m_session->setRemote(remoteIP, remotePort);
        m_timerID = startTimer(5000);
        return true;
    }else
    {
        delete m_session;
        m_session = Q_NULLPTR;
        return false;
    }
}

void UdpChannelDemo::onProc(const QByteArray &arry)
{
    NetReading *reading = dynamic_cast<NetReading *>(this);
    Q_ASSERT(reading);

    qDebug() << m_session->localAddress().toString() <<":"
             << m_session->localPort()
             << " 接收到来自"
             << reading->host().toString()
             << ":" << reading->port() << "数据:" << arry;
}

void UdpChannelDemo::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_timerID)
    {
        QString info = QDateTime::currentDateTime().toString();
        QByteArray array = info.toLatin1();
        if(m_session)
        {
            int writeSize = m_session->write(array);
            if( writeSize > 0)
            {
                qDebug() << "写入数据成功！";
            }else
            {
                qWarning()<< "写入数据失败！" << writeSize;
            }
        }
    }
}
